#Logtrack-ng - Module for printing a logging important messages
#Copyright (C) 2007 Jan Kucera
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

=head1 NAME

Logtrack::Debug;

=head1 DESCRIPTION

Module for printing and logging error or normal messages depending on chosen 
level of debug. Module works as singleton OOP object - it holds it's descriptor
 until # at least one instance of module exists

=head2 FUNCTIONS
=over 4

=item debug
=item debugln
=item errstr
=item errstrln
=item set_debug_level
=item set_file_descriptor


=cut
package Logtrack::Debug;

no strict 'refs';
no strict 'subs';

use Exporter;
use Term::ANSIColor qw(:constants); ;

my $singleton;

BEGIN {
	$singleton = {
		fd => 'STDERR',
		level => 1
	};
	bless $singleton, 'Logtrack::Debug';
}

sub new {
	my $class = shift;
	return $singleton;
}

sub DESTROY {
	my $self = shift;
	$self->{fd}->close();
}

sub set_debug_level {
	my ($self,$level) = @_;
	$self->{level} = $level;
}

sub set_file_descriptor {
	my ($self,$descriptor) = @_;
	$self->{fd}->close();
	$self->{fd} = $descriptor;
}

sub errstr {
	my ($self,$message) = @_;
	my $fd = $self->{fd};
	print $fd localtime(time) .': '. $message;
	print RED localtime(time) .': '. $message, RESET;
	
	autoflush $fd 1;
}

sub errstrln {
	my ($self,$message) = @_;
	my $fd = $self->{fd};
	print $fd localtime(time) .': '. $message ."\n";
	print RED localtime(time) .': '. $message, RESET ."\n";
	autoflush $fd 1;
}

sub debug  {
	my ($self,$message,$level) = @_;
	return if(not defined $level);
	
	print localtime(time) .': '. $message
		if((defined $level) && ($level <= $self->{level}) );
}

sub debugln {
	my ($self,$message,$level) = @_;
	return if(not defined $level);
	
	print localtime(time) .': '. $message ."\n"
		if($level <= $self->{level});
}

sub println {
	my ($self,$message,$level) = @_;
	return if(not defined $level);
	print $message ."\n"
		if($level <= $self->{level});
}
1;
